<template>
  <div class="bookstore-wrapper"> <!-- Add a root wrapper element -->
    <div class="bookstore-container">
      <!-- 顶部搜索栏 -->
      <div class="search-section">
        <div class="search-box">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索书名或作者..."
            @keyup.enter="handleSearch"
          />
          <button @click="handleSearch">搜索</button>
          <div class="block">
            <span class="demonstration">请选择图书分类<n></n></span>
            <el-cascader
              clearable
              v-model="value"
              :options="options"
              :props="props"
              @change="handleChange"
            ></el-cascader>
          </div>
        </div>
      </div>

      <!-- 书籍列表 -->
      <div class="books-section">
        <div v-if="loading" class="loading"> 加载中... </div>
        <div v-else-if="books.length === 0" class="no-data">
          暂无相关书籍
        </div>
        <div v-else class="books-grid">
          <div
            v-for="book in books"
            :key="book.bookId"
            class="book-card"
            @click="fetchBookDetail(book.bookId)"
          >
            <div class="book-cover">
              <img :src="book.bookImage" :alt="book.bookName" />
            </div>
            <div class="book-info">
              <h3 class="book-title">{{ book.bookName }}</h3>
              <p class="book-author">{{ book.author }}</p>
              <p class="book-price">￥{{ book.bookPrice }}</p>
              <div class="book-actions">
                <!-- 使用正确的比较运算符 === -->
                <button v-if="book.isFavorite ==1" @click.stop="addToCart(book)">取消收藏</button>
                <button v-else-if="book.isFavorite == 0" @click.stop="addToCart(book)">加入收藏</button>
              </div>

            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination" v-if="books.length > 0">
          <button :disabled="currentPage === 1" @click="changePage(currentPage - 1)">
            上一页
          </button>
          <span>{{ currentPage }} / {{ totalPages }}</span>
          <button
            :disabled="currentPage === totalPages"
            @click="changePage(currentPage + 1)"
          >
            下一页
          </button>
        </div>
      </div>

      <!-- 弹窗显示书籍详细信息 -->
      <div v-if="showDetail" class="modal">
        <div class="modal-content">
          <span class="close" @click="showDetail = false">&times;</span>
          <h2>{{ bookDetail.bookName }}</h2>
          <p>作者: {{ bookDetail.bookAuth }}</p>
          <p>价格: ￥{{ bookDetail.bookPrice }}</p>
          <p>出版社: {{ bookDetail.bookPress }}</p>
          <p>出版时间: {{ bookDetail.pressDate }}</p>
          <p>收藏量: {{ bookDetail.BookCollectionNum }}</p>
          <!-- 如果有其他详细信息，可以在这里添加 -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "BookStore",

  data() {
    return {
      value: [],
      options: [],
      props: {
        value: "typeId",
        label: "typeName",
        children: "children",
        checkStrictly: true,
      },
      books: [],
      bookDetail: {}, // 存储书籍详细信息
      searchQuery: '',
      currentPage: 1,
      pageSize: 4,
      totalPages: 1,
      loading: false,
      showDetail: false, // 控制弹窗显示
      error: null
    }
  },

  created() {
    this.fetchBooks();
    this.getBookType();
  },

  methods: {
    handleChange(value) {
      console.log('已选择的值: ', value);
    },
    getBookType() {
      this.$http.post("/bookType/selectBookType").then(resp => {
        this.options = resp.data.data;
      }).catch(error => {
        console.error('获取书籍分类失败:', error)
      });
    },
    async fetchBooks() {
      this.loading = true;
      try {
        const response = await this.$http.post('/bookInfo/selectAllBook', {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchQuery,
          typeId: this.value.length ? this.value[this.value.length - 1] : null,
        });
        if (response.data.code === 200) {
          this.books = response.data.data.list;
          this.totalPages = Math.ceil(response.data.data.total / this.pageSize);
        } else {
          this.$message.error(response.data.message || '获取书籍列表失败');
        }
      } catch (error) {
        console.error('获取书籍失败:', error);
        this.$message.error('网络错误，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    async fetchBookDetail(bookId) {

      try {
        const data= new FormData();
        data.append("bookId",bookId)
        const response = await this.$http.post('/bookInfo/getBookDetail', data);
        if (response.data.code === 200) {
          this.bookDetail = response.data.data;
          this.showDetail = true; // 显示弹窗
        } else {
          this.$message.error(response.data.message || '获取书籍详细信息失败');
        }
      } catch (error) {
        console.error('获取书籍详细信息失败:', error);
        this.$message.error('网络错误，请稍后重试');
      }
    },

    handleSearch() {
      this.currentPage = 1;
      this.fetchBooks();
    },

    changePage(page) {
      this.currentPage = page;
      this.fetchBooks();
    },

    viewBookDetail(bookId) {
      this.$router.push(`/book/${bookId}`);
    },

    async addToCart(book) {
      try {
        const data= new FormData();
        data.append("bookId",book.bookId)
        const response = await this.$http.post('/userInfo/collect',data
         )

        if (response.data.code === 200) {
          this.$message.success('操作成功');
             this.fetchBooks();
        } else {
          this.$message.error(response.data.message || '加入购物车失败');
        }
      } catch (error) {
        console.error('加入购物车失败:', error);
        this.$message.error('网络错误，请稍后重试');
      }
    }
  }
}
</script>

<style scoped>
.bookstore-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.search-section {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.search-box {
  display: flex;
  gap: 10px;
  flex: 1;
}

.search-box input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
}

.search-box input:focus {
  border-color: #409EFF;
}

button {
  padding: 8px 15px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #66b1ff;
}

button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.book-card {
  border: 1px solid #eee;
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s;
  cursor: pointer;
}

.book-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 3px 10px rgba(0,0,0,0.1);
}

.book-cover {
  width: 100%;
  padding-top: 125%;
  position: relative;
  overflow: hidden;
}

.book-cover img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.book-info {
  padding: 10px;
}

.book-title {
  margin: 0 0 5px;
  font-size: 14px;
  font-weight: bold;
  line-height: 1.2;
  height: 36px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.book-author {
  margin: 3px 0;
  color: #666;
  font-size: 12px;
}

.book-price {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
  margin: 8px 0;
}

.book-actions {
  display: flex;
  justify-content: center;
}

.book-actions button {
  width: 100%;
  background-color: #67c23a;
  padding: 6px;
}

.book-actions button:hover {
  background-color: #85ce61;
}

.loading, .no-data {
  text-align: center;
  padding: 40px;
  color: #666;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
}

.pagination span {
  color: #666;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  width: 80%;
  max-width: 500px;
  position: relative;
}

.close {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 18px;
  cursor: pointer;
}

@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
  }

  .books-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  }
}
</style>
